#!/usr/bin/env python
# -*- coding: utf-8 -*-
from datetime import datetime
from persistent import Persistent
from persistent.list import PersistentList

class Role(Persistent):
    """角色模型"""
    
    def __init__(self, rolename, description=None):
        """初始化角色
        
        Args:
            name (str): 角色名称
            description (str): 角色描述
        """
        super().__init__()
        self.rolename = rolename
        self.description = description or name
        self.permissions = PersistentList()  # 角色拥有的权限列表
        self.created = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        self.updated = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

        # 角色拥有的项目路径列表
        self.project_paths = PersistentList()
    
    def add_permission(self, permission_name):
        """为角色添加权限"""
        if permission_name not in self.permissions:
            self.permissions.append(permission_name)
            self.updated = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            self._p_changed = True
    
    def remove_permission(self, permission_name):
        """移除角色权限"""
        if permission_name in self.permissions:
            self.permissions.remove(permission_name)
            self.updated = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            self._p_changed = True
    
    def has_permission(self, permission_name):
        """检查角色是否具有指定权限"""
        return permission_name in self.permissions
    
    def to_dict(self):
        """转换为字典格式"""
        return {
            'name': self.name,
            'description': self.description,
            'permissions': list(self.permissions),
            'created': self.created.isoformat() if self.created else None,
            'updated': self.updated.isoformat() if self.updated else None
        }
